//
//  CallViewController.m
//  zuixin
//
//  Created by QJY on 14-8-18.
//  Copyright (c) 2014年 dingshenwangluokeji. All rights reserved.
//

#import "CallViewController.h"
#import "Header.h"
#import "NetAccess.h"
#import "AppDelegate.h"
#import "FMDBManager.h"
#import "DSHisViewController.h"
#import "KVobiject.h"
#import "NewGonfGaoViewController.h"
#import "AboutusViewController.h"
#import "AFNetworking.h"
#import "Base64Encry.h"


@interface CallViewController ()<UITextFieldDelegate,UIAlertViewDelegate>

@end
#define CONFIGURE_BUTTON(BTN,X,Y,TITLE,TAG) {\
self.BTN = [UIButton buttonWithType:UIButtonTypeCustom];\
[self.BTN setFrame:CGRectMake(X, Y-30, widthOfButton, heightOfButton)];\
[self.BTN setTintColor:[UIColor whiteColor]];\
[self.BTN setBackgroundColor:[UIColor blackColor]];\
[self.BTN setTag:TAG];\
[self.BTN addTarget:self action:@selector(onKeyPressed:) \
forControlEvents:UIControlEventTouchUpInside];\
[_views addSubview:self.BTN];\
}
#define PULL_DOWN_OFFSET 5.0

#define TAG_KEY_DIAL     111

#define TAG_KEY_UNDO     444
@implementation CallViewController
{
    UIView *contentView;
    BOOL down;
    NSString *_hj;
    UIButton *_btn;
    UIButton *_ghu;
    UILabel *_timelab;
    NSString*_timeStr;

    UITableView *_tabView;
    UIImageView *_imafg;
    UIButton *_labeh;
    UILabel *_labeh1;
    UIAlertView *_alertView;
    NSUserDefaults *users;
    AppDelegate *_app;
    NSMutableArray *_tellArray;
    NSArray *_arr;
    NSMutableDictionary*cellDict;
    NSInteger cellNumber;
     

    NSString *_cs;
    NSArray *_listItems;
    NSString *_string;
    NSMutableData *_data;
    UITextField *_thf12;
    UITextField *_thf15;
    //NetAccess *net;
    NSMutableArray *_hujb;
    NSArray*arry;
    NSInteger b;
    UIView *numberView;
    NSMutableArray *titleArry;
    NSMutableArray*imagArry;
    
    CGFloat heightOfButton;
    NSString*string;
    NSString*userId;
    NSString*_name;
    NSString*_word;
        NSInteger c;
    

    int currentVersion;
    NSString *_Version;
    NSString *_urlt;
    UIView*view;
    NSMutableArray *searchMutArry;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        users =[NSUserDefaults standardUserDefaults];
            _hujb =[[NSMutableArray alloc]init];
           searchMutArry=[[NSMutableArray alloc]init];
    }
    return self;
}
-(void)virds
{
    if(IOS7)
    {
        self.automaticallyAdjustsScrollViewInsets =NO;
        // 不透明的操作栏<br
        self.extendedLayoutIncludesOpaqueBars =NO;
        self.edgesForExtendedLayout =UIRectEdgeNone;
        self.modalPresentationCapturesStatusBarAppearance = NO;
//        UIImageView *statusBarView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 20)];
//       
//        statusBarView.image=[UIImage imageNamed:@"navgationbar.png"];
//        
//        [self.view addSubview:statusBarView];
    }
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    _timelab=[[UILabel alloc]init];
    _timelab.hidden=YES;
    //[_tabView reloadData];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self virds];
    [_tabView reloadData];
    [numberView setHidden:NO];
    //[_ghu setHidden:YES];
    FMDBManager *_manager = [FMDBManager sharedManager];
    _hujb=[_manager getAllUsers];
    if (IOS5) {
        if(DeviceHeight==568)
        {
            _views.frame =CGRectMake(0, 245-20+1+36, DeviceWidth, DeviceHeight-195-49-36);
            
        }
        if(DeviceHeight==480)
        {
            _views.frame =CGRectMake(0, DeviceHeight-284+1, 320,DeviceHeight-numberView.frame.size.height-20-49);
            _views.backgroundColor=[UIColor redColor];
        }
    }
    else
    {
        if(DeviceHeight==568)
        {
            _views.frame =CGRectMake(0, 245+36, DeviceWidth, DeviceHeight-195-49-36);
            
        }
        if(DeviceHeight==480)
        {
            _views.frame =CGRectMake(0, DeviceHeight-284+21, 320,DeviceHeight-numberView.frame.size.height-20-49);
            _views.backgroundColor=[UIColor redColor];
        }
        
    }
    
    
    
    
    
    
    NSUserDefaults *us =[NSUserDefaults standardUserDefaults];
    _tellArray =[NSMutableArray arrayWithArray:[us objectForKey:@"tellDemol"]];
    self.txtNumber.text =@"";
    [self.view addSubview:_views];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"tex" object:self.txtNumber.text];
    [_tabView reloadData];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"textField" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"hid" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"hidden" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"tex" object:nil];
}
- (void)viewDidLoad
{
      [[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    [super viewDidLoad];
    [self controllersd];
//    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(addInitIal) object:nil];
//    [thread start];
//    NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(GetImag) object:nil];
//    [thread1 start];
    
    //    self.navigationCo;ntroller.navigationBar.barStyle= UIBarStyleBlackTranslucent;字体颜色
    //状态栏字体颜色
    //   [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    //    self.view.backgroundColor=[UIColor blackColor];
    //    self.title=@"通话记录";
    //   [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navgationbar.png"] forBarMetrics:UIBarMetricsDefault];
    //    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
    //    statusBarView.backgroundColor=[UIColor blackColor];
    //    [self.view addSubview:statusBarView];
    //    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    down =NO;
    [self inith];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chage:) name:@"textField" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hid:) name:@"hid" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hidden:) name:@"hidden" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hidly:) name:@"tex" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(btckko:) name:@"textFig" object:nil];
    
    
    if(IOS5)
    {
        _tabView =[[UITableView alloc]initWithFrame:CGRectMake(0, 44, DeviceWidth, DeviceHeight-64) style:UITableViewStylePlain];
    }
    else
    {
        _tabView =[[UITableView alloc]initWithFrame:CGRectMake(0, 64, DeviceWidth, DeviceHeight-64) style:UITableViewStylePlain];
    }

    _tabView.delegate =self;
    _tabView.dataSource =self;
    [self.view addSubview:_tabView];
    if (IOS5) {
        self.txtNumber = [[UILabel alloc]initWithFrame:CGRectMake(0,0,DeviceWidth,44)];
    }
    else
    {
        self.txtNumber = [[UILabel alloc]initWithFrame:CGRectMake(0,20,DeviceWidth,44)];
    }
    self.txtNumber.font=[UIFont fontWithName:@"Arial-BoldItalicMT" size:28];
    self.txtNumber.hidden =YES;
    self.txtNumber.adjustsFontSizeToFitWidth=YES;
    self.txtNumber.text =@"";
    self.txtNumber.textAlignment=1;
    self.txtNumber.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"navgationbar.png"]];
    [self.view addSubview:self.txtNumber];
       [_tabView reloadData];
    [self checkUpdate];
    
	// Do any additional setup after loading the view.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (searchMutArry.count)
    {
        return [searchMutArry count];
    }
    else
    {
        return [_tellArray count];
    }

    
}
-(NSInteger )numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"ContactCell" ;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[ UITableViewCell alloc ] initWithStyle : UITableViewCellStyleSubtitle reuseIdentifier :cellIdentifier];
        UIImageView *imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tab.png"]];
        imageView.frame =CGRectMake(15, 15, 15, 15);
        
        UIImageView *imageView1 =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cellphone.png"]];
        imageView1.frame =CGRectMake(0, 0, 30, 30);
        
        cell.accessoryView=imageView1;
        [cell addSubview:imageView];
        _timelab=[[UILabel alloc]init];
        _timelab.frame= CGRectMake(170, 1,110 ,cell.frame.size.height-2);
        _timelab.backgroundColor=[UIColor whiteColor];
        _timelab.font=[UIFont systemFontOfSize:12];
        _timelab.textColor=[UIColor grayColor];
        _timelab.text=@"";
        _timelab.tag = 20;
        [cell addSubview:_timelab];
    }
   
    
    //[cell addSubview:_timelab];
    
    cell.textLabel.font= [UIFont fontWithName:@"Arial Rounded MT Bold" size:16];
    if (searchMutArry.count) {
        cell.textLabel.text=[NSString stringWithFormat:@"     %@",[[searchMutArry objectAtIndex:indexPath.row] objectForKey:@"SearchName"]];
        cell.detailTextLabel.text=[NSString stringWithFormat:@"     %@",[[searchMutArry objectAtIndex:indexPath.row] objectForKey:@"SearchNumber"]];
        UILabel *label = (UILabel *)[cell viewWithTag:20];
        label.text=@"";
    }
    else
    {
        NSInteger number2=[[_tellArray[indexPath.row]
                            objectForKey:@"Number"]integerValue];
        if (number2>1)
        {
            cell.textLabel.text=[NSString stringWithFormat:@"     %@(%ld)       ",[[_tellArray objectAtIndex:indexPath.row] objectForKey:@"Demolname"],(long)number2];
        }
        else
        {
            cell.textLabel.text=[NSString stringWithFormat:@"     %@       ",[[_tellArray objectAtIndex:indexPath.row] objectForKey:@"Demolname"]];
        }
        
        cell.detailTextLabel.text =[NSString stringWithFormat:@"     %@       ",[[_tellArray objectAtIndex:indexPath.row] objectForKey:@"Demol"]];
        UILabel *label = (UILabel *)[cell viewWithTag:20];
        label.text=[NSString stringWithFormat:@"%@",[[_tellArray objectAtIndex:indexPath.row] objectForKey:@"DemolTime"]];
        if (label.text==nil)
        {
            return NULL;
        }
        else
        {
            //[cell addSubview:label];
        }
    }
        return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array =[users objectForKey:@"newusers1"];
    NSDictionary *dict =[array objectAtIndex:0];
    if([dict objectForKey:@"username"]==nil)
    {
        UIAlertView *aa = [[UIAlertView alloc]initWithTitle:@"亲!还没绑定账号呢" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [aa show];
        return;
    }
    else
        
    {
        if (searchMutArry.count) {
            _cs =[NSString stringWithFormat:@"%@,%@",[[searchMutArry objectAtIndex:indexPath.row] objectForKey:@"SearchNumber"],[[searchMutArry objectAtIndex:indexPath.row] objectForKey:@"SearchName"]];
            _listItems = [_cs componentsSeparatedByString:@","];
            cellDict=[NSMutableDictionary dictionaryWithDictionary:[searchMutArry objectAtIndex:indexPath.row]];
            NSLog(@"WW%@",cellDict);
            // cellNumber=indexPath.row;
            
        }
        else
        {
            _cs =[NSString stringWithFormat:@"%@,%@",[[_tellArray objectAtIndex:indexPath.row] objectForKey:@"Demol"],[[_tellArray objectAtIndex:indexPath.row] objectForKey:@"Demolname"]];
            _listItems = [_cs componentsSeparatedByString:@","];
            cellDict=[NSMutableDictionary dictionaryWithDictionary:[_tellArray objectAtIndex:indexPath.row]];
            cellNumber=indexPath.row;
            
        }
        if([[[UIDevice currentDevice] systemVersion]floatValue]<6)
        {
            [self compar];
        }
            else
            {
                   _alertView = [[UIAlertView alloc]initWithTitle:@"亲！您是要拨号么" message:nil delegate:self cancelButtonTitle:@"呼叫" otherButtonTitles:@"取消",nil];
            _alertView.tag =52;
            [_alertView show];
            }
       
        
    }
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
}
-(void)getCurrentTimeOfLabel
{
    
    NSDate *  senddate=[NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"HH:mm"];
    
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"%@",locationString);
    
    //    _timelab.text=locationString;
    //    _timelab.font=[UIFont systemFontOfSize:12];
    NSDate* now = [NSDate date];
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit;
    NSDateComponents *dd = [cal components:unitFlags fromDate:now];
    // int y = [dd year];
    NSInteger m = [dd month] ;
    NSInteger d = [dd day];
    NSString *day;
    day=[NSString stringWithFormat:@"%ld",(long)d];
    if (d<10) {
        day=[NSString stringWithFormat:@"0%ld",(long)d];
    }
    
    _timelab.text=[NSString stringWithFormat:@"%ld-%@  %@",(long)m,day,locationString];
    _timeStr=[NSString stringWithFormat:@"%ld-%@  %@",(long)m,day,locationString];
}
-(void)compar
{
    DSHisViewController *call =[[DSHisViewController alloc]init];
    call.tellName =_listItems;
    
    [self getCurrentTimeOfLabel];
    
    
    if (searchMutArry.count) {
        NSLog(@"WW0%@",cellDict);
        NSLog(@"WW1%@",_tellArray);
        NSMutableArray*demoMutArry=[NSMutableArray arrayWithCapacity:_tellArray.count];
        for (int i=0; i<_tellArray.count; i++)
        {
            demoMutArry[i]=[_tellArray[i] objectForKey:@"Demol"];
        }
        NSLog(@"rrr0%@",demoMutArry);
        NSLog(@"rrr1%@",[cellDict objectForKey:@"SearchNumber"]);
        if ([demoMutArry containsObject:[cellDict objectForKey:@"SearchNumber"]])
        {
            NSInteger index=  [demoMutArry indexOfObject:[cellDict objectForKey:@"SearchNumber"]];
            cellNumber=index;
            cellDict=[NSMutableDictionary dictionaryWithDictionary:_tellArray[index]];
            NSLog(@"WW3%@",cellDict);
            [cellDict setObject:_timeStr forKey:@"DemolTime"];
            NSInteger number=[[cellDict objectForKey:@"Number"]integerValue];
            number++;
            [cellDict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"Number"];
            [_tellArray removeObjectAtIndex:cellNumber];
            
        }
        else
        {
            //NSInteger number1=1;
            NSLog(@"eee1%@",cellDict);
            NSMutableDictionary*dic=cellDict;
            NSLog(@"eee10%@",dic);
            cellDict=[[NSMutableDictionary alloc]init];
            NSLog(@"eee11%@",cellDict);
            [cellDict setObject:[dic objectForKey:@"SearchNumber"] forKey:@"Demol"];
            [cellDict setObject:[dic objectForKey:@"SearchName"] forKey:@"Demolname"];
            [cellDict setObject:_timeStr forKey:@"DemolTime"];
            NSLog(@"eee2%@",cellDict);
            [cellDict setObject:@"1" forKey:@"Number"];
            
        }
    }
    
    else
    {
        [cellDict setObject:_timeStr forKey:@"DemolTime"];
        NSInteger number=[[cellDict objectForKey:@"Number"]integerValue];
        number++;
        [cellDict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"Number"];
        [_tellArray removeObjectAtIndex:cellNumber];
    }
    
    [_tellArray insertObject:cellDict atIndex:0];
    [[NSUserDefaults standardUserDefaults]setObject:_tellArray forKey:@"tellDemol"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    [self presentViewController:call animated:YES completion:nil];
}

-(void)hidly:(NSNotification *)meng
{
    self.txtNumber.hidden =YES;
     [searchMutArry removeAllObjects];
    [numberView setHidden:NO];
    [_btn setHidden:NO];
}
-(void)hidden:(NSNotification *)feng
{
    [UIView animateWithDuration:1.0f animations:^{
        _views.hidden =NO;
        _ghu.hidden=YES;
        down=NO;
        self.txtNumber.text=@"";
    }];
}
-(void)hid:(NSNotification *)hui
{
    [UIView animateWithDuration:1.0f animations:^{
        _views.hidden =YES;
    }];
}
-(void)chage:(NSNotification *)note
{
    if (_txtNumber.text.length>0)
    {[self hideTabBar];
        self.tabBarController.tabBar.hidden =YES;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"hidendleTAb" object:self.tabBarController.tabBar];
        [self.txtNumber setHidden:NO];
    }
}
-(void)btckko:(NSNotification *)hgfd
{
    if(self.txtNumber.text==nil)
    {
        NSLog(@"Error");
    }
    else
    {
        [self btncjy];
    }
}
-(void)btncjy
{
    NSArray *array =[users objectForKey:@"newusers1"];
    NSDictionary *dict =[array objectAtIndex:0];
    if([dict objectForKey:@"username"]==nil)
    {
        _alertView = [[UIAlertView alloc]initWithTitle:@"用户登录" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        _alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
        [_alertView show];
        return;
    }
    else
    {
        [self dianji];
        return;
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==5)
    {
        if(buttonIndex==1) {
            NSLog(@"da");
            NewGonfGaoViewController*go=[[NewGonfGaoViewController alloc]init];
            go.urlStr=[arry[0] objectForKey:@"Links"];
            [self presentViewController:go animated:YES completion:nil];
            //[self.tabBarController setSelectedIndex:2];
        }
    }
    if(alertView.tag ==52)
    {
        if(buttonIndex==0)
        {
            [self compar];
        }
    }
        if (alertView.tag==61) {
            if (buttonIndex != [alertView cancelButtonIndex])
            {
                NSLog(@"qqqqq%@",_urlt);
                NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_urlt ]];
                [[UIApplication sharedApplication] openURL:url];
            }
            
        }
   

    }
    
-(NSString*)judge:(NSString*)number boolOf:(NSMutableArray*)allpeople
{
    NSString *name=@"";
    for (int i=0; i<allpeople.count; i++) {
        if ([allpeople[i] containsObject:number]) {
            // NSInteger integer=[allpeople[i] indexOfObject:number];
            name=[allpeople[i] objectAtIndex:0];
            
        }
    }
    return name;
}

-(void)dianji
{
    [self getCurrentTimeOfLabel];
    
    if(_txtNumber.text.length)
    {
        
        
        //获取被叫号码
        self.PhoneNumber=_txtNumber.text;
        NSUserDefaults *users1=[NSUserDefaults standardUserDefaults];
        
        [users1 setObject:_txtNumber.text forKey:@"postName"];
        NSMutableArray *allpeopleMutArry=[NSMutableArray arrayWithArray:[users1 objectForKey:@"AllpeopNumber"]];
        NSLog(@"ss%@",allpeopleMutArry);
        [users1 synchronize];
        
        _hj=[self judge:_txtNumber.text boolOf:allpeopleMutArry];
    
        NSLog(@"qq%@",_hj);
        if (_hj.length==0) {
            _hj=@"联系人";
        }
        
        NSMutableArray *sdk =[[NSMutableArray alloc]initWithObjects:_txtNumber.text,_hj,nil];
        NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
        NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
        NSInteger number=1;
          NSMutableArray*demoMutArry;
        if([myUserDefaults objectForKey:@"tellDemol"])
        {
            demoMutArry=[NSMutableArray arrayWithCapacity:_tellArray.count];
            
            for (int i=0; i<_tellArray.count; i++)
            {
                demoMutArry[i]=[_tellArray[i] objectForKey:@"Demol"];
            }
            NSLog(@"aaa%@",demoMutArry);
            if ([demoMutArry containsObject:_txtNumber.text])
                
            {
                NSInteger index=  [demoMutArry indexOfObject:_txtNumber.text];
                
                NSInteger number1=[[_tellArray[index] objectForKey:@"Number"]integerValue];
                NSLog(@"ss%ld",(long)number1);
                number1++;
                
                NSMutableDictionary*  dict1=[NSMutableDictionary dictionaryWithDictionary:_tellArray[index]];
                [dict1 setObject:_timelab.text forKey:@"DemolTime"];
                [dict1 setObject:[NSString stringWithFormat:@"%ld",(long)number1] forKey:@"Number"];
                [_tellArray removeObjectAtIndex:index];
                
                [_tellArray insertObject:dict1 atIndex:0];
            }
            else
            {
                [dict setObject:_txtNumber.text forKey:@"Demol"];
                [dict setObject:_hj forKey:@"Demolname"];
                [dict setObject:_timelab.text forKey:@"DemolTime"];
                [dict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"Number"];
            }
            
            NSLog(@"aaa%@",dict);
            if ([dict count]==0) {
                
                
            }
            else
            {
                [_tellArray insertObject:dict atIndex:0];
            }
            
            
            
            
            [myUserDefaults setObject:_tellArray forKey:@"tellDemol"];
            
        }
        else
        {
            _tellArray= [[NSMutableArray alloc] initWithCapacity:60];
            if(_tellArray.count>=60)
            {
                [_tellArray removeObjectAtIndex:0];
            }
            [dict setObject:_txtNumber.text forKey:@"Demol"];
            [dict setObject:_hj forKey:@"Demolname"];
            [dict setObject:_timelab.text forKey:@"DemolTime"];
            [dict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"Number"];
            NSLog(@"ss%ld",(long)number);
            [_tellArray insertObject:dict atIndex:0];
            [myUserDefaults setObject:_tellArray forKey:@"tellDemol"];
        }
        [myUserDefaults synchronize];
        [_tabView reloadData];
        DSHisViewController *cael =[[DSHisViewController alloc]init];
        cael.tellName=sdk;
        [self presentViewController:cael animated:YES completion:^{
            
        }];
    }
}
- (void)hideTabBar {
    
    if (self.tabBarController.tabBar.hidden == YES) {
        return;
    }
    if ( [[self.tabBarController.view.subviews objectAtIndex:2] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = YES;
}
-(void)move
{
//    int time=_labeh1.frame.size.width/25;
//    if (time<=2) {
//        time=2;
//    }
    [UIView animateWithDuration:8 animations:^{
        _labeh1.frame=CGRectMake(-_labeh1.frame.size.width, 0, _labeh1.frame.size.width, 44);
//        if (_labeh1.frame.origin.x<0)
//        {
//            _labeh1.frame=CGRectMake(0, 0, _labeh1.frame.size.width-_labeh1.frame.origin.x, 44);
//        }
        
        //label1.frame=CGRectMake(120, 0, 120, 50);
    } completion:^(BOOL finished) {
        _labeh1.frame = CGRectMake(220, 0, _labeh1.frame.size.width, 44);
              [self move];
    }];

}
-(void)inith
{
    
    _views=[[UIView alloc]init];
    _tellArray =[NSMutableArray array];
    _app =[UIApplication sharedApplication].delegate;
    CGRect frame = [[UIScreen mainScreen]applicationFrame];
    frame.size.height /= 1.1;
    if (self) {
        CGFloat heightOfTextField = 30.0;
        if (IOS5) {
            numberView =[[UIView alloc]initWithFrame:CGRectMake(0, 0
                                                             , DeviceWidth, 44)];
        }
        else
        {
            numberView =[[UIView alloc]initWithFrame:CGRectMake(0, 20
                                                             , DeviceWidth, 44)];
           // numberView.backgroundColor=[UIColor redColor];
        }
        numberView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed: @"navgationbar.png"]];
        [self.view addSubview:numberView];
        view=[[UIView alloc]initWithFrame:CGRectMake(100, 0, DeviceWidth-view.frame.origin.x, 44)];
        //view.backgroundColor=[UIColor redColor];
        [numberView addSubview:view];
        _labeh1=[[UILabel alloc]init];
//        _labeh1.text=@"欢迎使用波司登电话";
        _labeh1.backgroundColor=[UIColor clearColor];
//      
//        [numberView addSubview:_labeh1];
        [self labelForSize];
#pragma 滑动的字
       [self move];
        _labeh=[UIButton buttonWithType:UIButtonTypeCustom];
//        _labeh.frame=CGRectMake(0, 0, 100, 44);
        _labeh.frame=CGRectMake(0, 0, numberView.frame.size.width, numberView.frame.size.height);
         [numberView addSubview:_labeh];
         [_labeh setTitle:@"通话记录" forState:UIControlStateNormal];
        [numberView addSubview:_labeh];
        _labeh.titleLabel.textAlignment =NSTextAlignmentCenter;
        //_labeh.highlighted=YES;
//        _labeh.titleLabel.font=[UIFont fontWithName:@"Courier-Bold" size:16];
        _labeh.titleLabel.font=[UIFont fontWithName:@"Courier-Bold" size:23];

        [_labeh setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _labeh.backgroundColor=[UIColor colorWithRed:24/255.0 green:158/255.0 blue:231.0/255 alpha:1];
        _labeh.titleLabel.backgroundColor=[UIColor colorWithRed:24/255.0 green:158/255.0 blue:231.0/255 alpha:1];

        
        
        
        if (DeviceHeight==568) {
            heightOfButton = frame.size.height / 5.0 - heightOfTextField-10;
        }
        else
        {
            heightOfButton = frame.size.height / 5.0 - heightOfTextField;
        }
        CGFloat widthOfButton = frame.size.width / 3.0;
        //configure the number key
        CONFIGURE_BUTTON(btn1, 0, heightOfTextField
                         , @"1",1);
        
        [self.btn1 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_1_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn1 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_1_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btn2, widthOfButton , heightOfTextField, @"2",2);
        [self.btn2 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_2_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn2 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_2_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btn3, widthOfButton*2, heightOfTextField, @"3",3);
        [self.btn3 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_3_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn3 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_3_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btn4, 0, heightOfButton + heightOfTextField
                         , @"4",4);
        [self.btn4 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_4_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn4 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_4_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btn5, widthOfButton, heightOfButton + heightOfTextField, @"5",5);
        [self.btn5 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_5_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn5 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_5_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btn6, widthOfButton*2, heightOfButton + heightOfTextField, @"6",6);
        [self.btn6 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_6_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn6 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_6_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btn7, 0, heightOfButton*2 + heightOfTextField, @"7",7);
        [self.btn7 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_7_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn7 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_7_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btn8, widthOfButton, heightOfButton*2 + heightOfTextField, @"8",8);
        [self.btn8 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_8_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn8 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_8_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btn9, widthOfButton*2, heightOfButton*2 + heightOfTextField, @"9",9);
        [self.btn9 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_9_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn9 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_9_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btn0, widthOfButton, heightOfButton*3 + heightOfTextField, @"0",0);
        [self.btn0 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_11_nor.png"]
                             forState:UIControlStateNormal];
        [self.btn0 setBackgroundImage:[UIImage imageNamed:@"dialplate_key_11_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btnDial,0,heightOfButton*3 + heightOfTextField, @"Dial",TAG_KEY_DIAL);
        [self.btnDial  setBackgroundImage:[UIImage imageNamed:@"dialplate_key_10_nor.png"]forState:UIControlStateNormal];
        [self.btnDial setBackgroundImage:[UIImage imageNamed:@"dialplate_key_10_select.png"] forState:UIControlStateHighlighted];
        CONFIGURE_BUTTON(btnUndo, widthOfButton*2, heightOfButton*3 + heightOfTextField, @"Undo",TAG_KEY_UNDO);
        [self.btnUndo setBackgroundImage:[UIImage imageNamed:@"dialplate_key_12_nor.png"]
                                forState:UIControlStateNormal];
        [self.btnUndo setBackgroundImage:[UIImage imageNamed:@"dialplate_key_12_select.png"] forState:UIControlStateHighlighted];
        mIsLayOn = NO;
        [self setLayOn:mIsLayOn];
        _views.backgroundColor = [UIColor redColor];
    }
}
-(void)btnCck:(id)sender
{
    if(down==NO)
    {
        //动画效果
        [UIView animateWithDuration:0.01 animations:^{
            //同步阻塞调用
            [[NSNotificationCenter defaultCenter]postNotificationName:@"hid" object:_views];
        } completion:^(BOOL finished) {
            down=YES;
        }];
    }
    if(down==YES)
    {
        [UIView animateWithDuration:0.01 animations:^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"hidden" object:_views];
            _ghu.hidden =YES;
        } completion:^(BOOL finished) {
            down=NO;
        }];
    }
}
-(void)setLayOn:(BOOL)isLayOn
{
    CGFloat adjustOffset = (_views.frame.size.height )/8.0 + PULL_DOWN_OFFSET;
    if (isLayOn == YES) {
        adjustOffset *= 1;
    }
}
-(void)tap:(UILongPressGestureRecognizer*)sender
{
    self.txtNumber.text=@"";
    [[NSNotificationCenter defaultCenter]postNotificationName:@"tex" object:self.txtNumber.text];
}

-(void)onKeyPressed:(id)sender
{
    //    UIButton *button = (UIButton *)sender;
    //    button.selected = !button.selected;
    //    [NSThread sleepForTimeInterval:2.0f];
    //    button.selected=!button.selected;
    NSInteger tag = [sender tag];
    NSString *text = self.txtNumber.text;
    switch (tag) {
        case TAG_KEY_DIAL:
            if (TAG_KEY_DIAL) {
                if(down==NO)
                {
                    if(self.txtNumber.text.length!=0)
                    {
                    }else
                    {
                        [UIView animateWithDuration:0.01 animations:^{
                            [[NSNotificationCenter defaultCenter]postNotificationName:@"hid" object:_views];
                            _ghu =[UIButton buttonWithType:UIButtonTypeCustom];
                            if(DeviceHeight==480)
                            {
                                _ghu.frame =CGRectMake(140,370, 40, 40);
                            }if(DeviceHeight==568)
                            {
                                _ghu.frame =CGRectMake(140,450, 40, 40);
                            }
                            [_ghu setImage:[UIImage imageNamed:@"deepbluebackup.png"] forState:UIControlStateNormal];
                            [_ghu addTarget:self action:@selector(btnCck:) forControlEvents:UIControlEventTouchUpInside];
                            [self.view addSubview:_ghu];
                        } completion:^(BOOL finished) {
                            down=YES;
                        }];
                    }
                }
            }
            break;
        case TAG_KEY_UNDO:
        { UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
            [sender addGestureRecognizer:longPress];

            if (TAG_KEY_UNDO) {
                NSString *text = self.txtNumber.text;
                if (text.length) {
                    self.txtNumber.text = [text stringByReplacingCharactersInRange:NSMakeRange(text.length-1, 1)withString:@""];
//                     [self getSearchArry:self.txtNumber.text];
                    if(self.txtNumber.text.length==0)
                    {
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"tex" object:self.txtNumber.text];
                    }
                }
                
            }
            break;}
        default:
            self.txtNumber.text = [NSString stringWithFormat:@"%@%ld",text,(long)tag];
//            [self getSearchArry:self.txtNumber.text];
            if(self.txtNumber.text .length>0)
            {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"textField" object:self.txtNumber.text];
            }
            break;
    }
}

-(void)GetImag
{

        NSString *str1=[NSString stringWithFormat:@"http://oemapi2.leehuu.cn/api/adv/GetAdvByUser?userId=%@&Page=1&PageSize=6",userId];
   
    NSURL *url1 = [NSURL URLWithString:[str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request1 = [NSURLRequest requestWithURL:url1];
    AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
    [operation1 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation1, id responseObject) {
        NSString *html1 = operation1.responseString;
        NSData* data1=[html1 dataUsingEncoding:NSUTF8StringEncoding];
        if (data1) {
            id dict1=[NSJSONSerialization  JSONObjectWithData:data1 options:0 error:nil];
            NSLog(@"111111111%@",dict1);
            
            NSArray*arry2 =[dict1 objectForKey:@"advs"];
            NSLog(@"555%@",arry2);
            if (arry2.count>0&&arry2) {
                titleArry=[[NSMutableArray alloc]init];
                imagArry=[[NSMutableArray alloc]init];
                for (int i=0; i<arry2.count; i++) {
                    
                    NSString*str=[arry2[i]objectForKey:@"Title"];
                    
                    titleArry[i]=str;
                    NSString*str1=[arry2[i]objectForKey:@"PicPath"];
                    
                        imagArry[i]=str1;
            
                }
                [[NSUserDefaults standardUserDefaults]setObject:imagArry forKey:@"ImageArry"];
                [[NSUserDefaults standardUserDefaults]synchronize];
             
               [self labelForSize];
                
            }
            else
            {
//                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"网络信号不好，请稍后查询" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                [alertView show];
                return ;
            }
            
        }
        else
        {
//            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"网络信号不好，请稍后查询"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alertView show];
            return ;
        }
        
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"服务器异常，无法获取商户广告数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        [alert show];
    }];
    
    NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
    [queue1 addOperation:operation1];
    
    
}
//自动检测版本
-(void)checkUpdate
{
    c=[[NSUserDefaults standardUserDefaults]integerForKey:@"C"];
    if (!c) {
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://oemapi2.leehuu.cn/api/agent/clientinfo?userid=2645421&os=2"]];
        if (data==nil) {
//            UIAlertView*alertview=[[UIAlertView alloc]initWithTitle:@"提示" message:@"网络信号不好" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [alertview show];
            return;
        }
        else
        {
            NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            _Version =[dict objectForKey:@"VersionNumber"];
            _urlt =[dict objectForKey:@"Url"];
            
        }
        
        
        NSString * sLastVersion= [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey]];
        NSString* newsLastVersion=[sLastVersion substringToIndex:5];
        //取当前的版本
        if (_Version!=nil&&(![_Version isEqual:[NSNull null]])) {
            
            NSString *sLastVersion1=[NSString stringWithFormat:@"%@%@%@",[sLastVersion substringToIndex:1],[sLastVersion substringWithRange:NSMakeRange(2, 1)],[sLastVersion substringWithRange:NSMakeRange(4, 1)]];
            
            NSString *_Version1=[NSString stringWithFormat:@"%@%@%@",[_Version substringToIndex:1],[_Version substringWithRange:NSMakeRange(2, 1)],[_Version substringWithRange:NSMakeRange(4, 1)]];
            if ([sLastVersion1 intValue]< [_Version1 intValue])
            {
                NSString*mess=[NSString stringWithFormat:@"最新版本号为:%@\n当前版本号为:%@",_Version,newsLastVersion];
                UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"升级提示"message:mess delegate:self cancelButtonTitle:@"以后再说" otherButtonTitles:@"马上更新",nil];
                av.delegate=self;
                av.tag =61;
                [av show];
                c++;
                [[NSUserDefaults standardUserDefaults]setInteger:c forKey:@"C"];
            }
            else
            {
                return;
            }
            
        }else
        {
            return;
        }
    }
    else
    {
        return;
    }
}


-(void)labelForSize
{
//    string =titleArry[0];
//    for (int i=1; i<titleArry.count; i++) {
//        string=[string stringByAppendingString:[NSString stringWithFormat:@"            %@",titleArry[i]]];
//    }
//    NSLog(@"11111%@",string);
 //string=@"sdkfj";
    
//    _labeh1.text=@"欢迎使用理念电话";
    _labeh1.textAlignment=1;
    _labeh1.numberOfLines=1;
    [_labeh1 setLineBreakMode:NSLineBreakByCharWrapping];
    _labeh1.font=[UIFont fontWithName:@"Courier-Bold" size:22];
    _labeh1.backgroundColor=[UIColor clearColor];
    CGRect bounds=[_labeh1 textRectForBounds:CGRectMake(0, 0, 4000, 44) limitedToNumberOfLines:0];
    _labeh1.frame=bounds;
    // _labeh1.backgroundColor=[UIColor yellowColor];
    _labeh1.frame=CGRectMake(-_labeh1.frame.size.width-20, 0, _labeh1.frame.size.width, 44);
    _labeh1.textColor=[UIColor blackColor];
    NSLog(@"www%@",_labeh1);
    //[view addSubview:_labeh1];
    
   

    
    
}
-(void)getSearchArry:(NSString*)number
{
    NSLog(@"1111");
    NSUserDefaults *users1=[NSUserDefaults standardUserDefaults];
    NSMutableArray *allpeopleMutArry=[NSMutableArray arrayWithArray:[users1 objectForKey:@"AllpeopNumber"]];
   // NSLog(@"ss%@",allpeopleMutArry);
    [users1 synchronize];
    
    [searchMutArry removeAllObjects];
    for (int i=0; i<allpeopleMutArry.count; i++) {
        // NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@",number];
        for (int j=0; j<6; j++) {
            BOOL isHave=[allpeopleMutArry[i][j] hasPrefix:number];
            NSMutableDictionary*dic=[[NSMutableDictionary alloc]init];
            if (isHave==YES) {
                [dic setObject:allpeopleMutArry[i][0] forKey:@"SearchName"];
                [dic setObject:allpeopleMutArry[i][j] forKey:@"SearchNumber"];
                [searchMutArry addObject:dic];
                [_tabView reloadData];
            }
            else
            {
                [_tabView reloadData];
                
            }
            
        }
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"tex" object:self.txtNumber.text];
}

//- (UIStatusBarStyle)preferredStatusBarStyle
//{
//    return UIStatusBarStyleDefault;
//}
//- (BOOL)prefersStatusBarHidden
//{
//    return NO;
//}
-(void)controllersd
{
    users =[NSUserDefaults standardUserDefaults];
    NSArray *array =[users objectForKey:@"newusers1"];
    NSDictionary *dict =[array objectAtIndex:0];
    
    _name =[dict objectForKey:@"username"];
    _word=[dict objectForKey:@"userword"];
  //  userId=[dict objectForKey:@"userID" ];
    //dicts=[users objectForKey:@"Dic"];
    //NSLog(@"qq%@",userId);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
